package com.dongdongshop.service.impl;

import com.dongdongshop.config.MyFreemarkerConfig;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.FreemarkerService;
import com.dongdongshop.service.TbGoodsService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FreemarkerServiceImpl implements FreemarkerService {

    //注入FreeMarkerConfigurer
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    //注入goods service
    @DubboReference
    private TbGoodsService tbGoodsService;

    //生成页面
    @Override
    public void createPage(Long goodsId) {
        //第一步:创建一个Configuration 对象;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //第四步:加载一个模板,创建一个模板对象
        FileWriter writer = null;
        try {
            Template template = configuration.getTemplate("item.ftl");
            //创建一个map;也可以是pojo,一般使用map;
            Map map = new HashMap<>();
            //调用goods接口查询数据(根据id查询数据)
            TbGoods tbGoods = tbGoodsService.getGoodsById(goodsId);
            //调用goods接口查询TbGoodsDesc数据(根据id查询数据)
            TbGoodsDesc tbGoodsDesc = tbGoodsService.getGoodsDescById(goodsId);
            //调用goods接口查询TbItem数据(根据id查询数据)
            List<TbItem> list = tbGoodsService.getTbItemByGoodsId(goodsId);
            map.put("goods",tbGoods);
            map.put("GoodsDesc",tbGoodsDesc);
            map.put("TbItem",list);
            //第六步:创建一个 writer 对象 一般创建一个 FileWriter 对象,指定生成文件名
            writer = new FileWriter("E:\\freemarker\\" + goodsId + ".html");
            //第七步:调用模板对象 process 方法输出文件
            template.process(map, writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                //关流
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
